# -*- encoding:utf8 -*-
from django.shortcuts import render
from django.http import HttpResponse
import json
import models
import control

# Create your views here.
def set(request):
    user=request.GET.get('user')
    if user:
        request.session['my_user']=user
        return HttpResponse('设置user成功')
    else:
        return HttpResponse('输入合理的键值对')
    
def main(request):
    jiemu_list = models.Jiemu.objects.all()
    dc = {
        'jiemu_list':jiemu_list
    }
    return render(request,'nianhui/nianhui.html',context=dc)

def jiemu(request,jiemu_id):
    user = request.session.get('my_user')
 
    can_zhan ='true'
    if request.method == 'GET':  
        if not user:
            can_zhan='false'        
        jm,al_zhan= control.already_zhan(user,jiemu_id)
        if al_zhan:
            can_zhan='false'
        if jm:
            jiemu_html= jm.content
            dc={
                'number' :jm.number(),
                'jiemu_html':jiemu_html,
                'can_zhan':can_zhan
            }
            return render(request,'nianhui/jiemu.html',context=dc)   
        else:
            return HttpResponse('节目不存在，请不要乱入')
    else:       # post json
        dc= json.loads(request.body)
        if dc.get('operation') == 'dian_zhan':   # 点赞 触发
            jm,al_zhan= control.already_zhan(user,jiemu_id)
            number=control.dian_zhan(user,jm)
            response_data={
                'msg':'投票成功！',
                'number':number
            }
        else:   # 没有对应的操作
            response_data={
                'status':'erro'
            }
        return HttpResponse(json.dumps(response_data), content_type="application/json") 

# ------------------下面的函数无用了--------等哈删除

def getjson(request):
    response_data={
        'jiemu':'<div>this is jiemu html</div>',
        'number':100
        }

    return HttpResponse(json.dumps(response_data), content_type="application/json")    

def postjson(request):
    dc= json.loads(request.body)
    if dc.pop('operation') =='dian_zhan':
        pass
    number = save_zhan_number()
    response_data={
    'jiemu':'<div><a href="aaa">这个是节目链接</a></div>',
    'number':number
    }
    return HttpResponse(json.dumps(response_data), content_type="application/json")    

def get_number(order_id):
    number =0
    jiemu = models.Jiemu.objects.get(jiemu_id=order_id)
    if jiemu:
        number = len( jiemu.zhan_list.split(',') )
    return number
        